#!/usr/bin/env bash

set -euo pipefail

cd "$(dirname "${0}")/.."

checkout_repo() {
  local -r path="${1}"
  local -r repo="${2}"
  local -r sha="${3}"
  local -r folder="${4:-}"

  echo "Checking out github.com/${repo}#${sha}${folder:+" (${folder})"} in ${path}"

  mkdir -p "${path}"
  pushd "${path}" >/dev/null

  if [[ ! -d ".git" ]]; then
    git init --quiet
    git remote add origin "https://github.com/${repo}.git"
    if [[ ! -z "${folder}" ]]; then
      git sparse-checkout set --cone
      git sparse-checkout set "${folder}"
    fi
    git fetch --quiet --depth 1 origin "${sha}"
  elif [[ "${sha}" != "$(git rev-parse HEAD)" ]]; then
    git fetch --quiet --depth 1 origin "${sha}"
  fi

  git checkout --quiet FETCH_HEAD

  popd >/dev/null

  echo
}

checkout_repo "./examples/apisix" "apache/apisix" "4419d0d8eb3daf901a1cf6fd4d2f806e579dced9" "apisix"
checkout_repo "./examples/kong" "Kong/kong" "3365f489532d475e05859cbc317d813bf927f362" "kong"
checkout_repo "./examples/lua" "lua/lua" "e15f1f2bb7a38a3c94519294d031e48508d65006"
checkout_repo "./examples/luvit" "luvit/luvit" "a8c708e064cc1d60ecca8d8ca00bc28fa2e49eeb"
checkout_repo "./examples/neovim" "neovim/neovim" "15c684b358b0165d0874ba08ab6ac0976c86cc0f" "runtime"
checkout_repo "./examples/xmake" "xmake-io/xmake" "cc343fcbf078ea5960aefa946c836f3d3fd4863c"

parse_examples() {
  local -r known_failures="$(cat script/known_failures.txt)"

  tree-sitter parse --quiet \
    "./examples/apisix/apisix/**/*.lua" \
    "./examples/kong/kong/**/*.lua" \
    "./examples/lua/**/*.lua" \
    "./examples/luvit/**/*.lua" \
    "./examples/neovim/runtime/**/*.lua" \
    "./examples/xmake/**/*.lua" \
    $(for file in ${known_failures}; do echo "!${file}"; done)

  declare -r example_count=$(find ./examples -name "*.lua" | wc -l)
  declare -r failure_count=$(wc -w <<< "${known_failures}")
  declare -r success_count=$(( ${example_count} - ${failure_count} ))
  declare -r success_percent=$(bc -l <<< "100*${success_count}/${example_count}")

  printf \
    "[Lua] Successfully parsed %d of %d example files (%.1f%%)\n" \
    ${success_count} ${example_count} ${success_percent}
}

parse_examples
